package str;

import java.util.HashMap;
import java.util.HashSet;

/**
 * @author : Rookie
 * @description : 最长无重复字串
 * @date : 2023/10/15
 */
public class LongestNoRepeatSubStr {

    public static void main(String[] args) {
        String str = "gdecdfecwvbre";
        System.out.println(solve1(str));
        System.out.println(solve2(str));
    }

    private static int solve1(String str) {
        HashSet<Character> set = new HashSet<>(str.length());
        int slow =0,maxLen =0;
        for (int fast = 0; fast < str.length(); fast++) {
            char c = str.charAt(fast);
            if (set.contains(c)) {
               // 如果当前集合中有这个字符
                set.remove(str.charAt(slow));
                slow++;
            } else {
                set.add(c);
                maxLen = Math.max(maxLen,fast-slow);
            }
        }
        return maxLen;
    }

    private static int solve2(String str) {
        int slow = 0,maxLen =0;
        HashMap<Character, Integer> hashMap = new HashMap<>();
        for (int fast = 0; fast < str.length(); fast++) {
            char c = str.charAt(fast);
            // 如果hash表中存在当前元素，直接跳转到当前元素索引+1处
            if (hashMap.containsKey(c)) {
                // 当前的slow可能已经在某个重复字符之后了
                slow = Math.max(slow,hashMap.get(c) + 1);
            }
            maxLen = Math.max(maxLen,fast-slow);
            hashMap.put(c,fast);
        }
        return maxLen;
    }
}
